<template>
  <div class="login-container">
    <div class="left">
      <div class="title">重症监护系统 V2.0</div>
      <div class="sub-title">我们关心您的医疗质量与安全 !</div>
      <img class="hospital-scene" src="../../icons/img/hospital-scene.png" />
    </div>
    <div class="right">
      <div class="content">
        <img src="../../icons/img/logo.png" class="logo" />
        <div class="login-title">账号登录</div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <el-form-item prop="tenantId" v-if="tenantList.length > 0">
            <span class="svg-container">
              <svg-icon
                slot="prefix"
                icon-class="peoples"
                class="el-input__icon input-icon"
              />
            </span>
            <el-select
              v-model="loginForm.tenantId"
              ref="tenantId"
              name="tenantId"
              placeholder="请选择"
              @change="depChange"
            >
              <el-option
                v-for="item in tenantList"
                :key="item.tenantId"
                :label="item.name"
                :value="item.tenantId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="loginName">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="loginName"
              v-model="loginForm.loginName"
              placeholder="用户名"
              name="loginName"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span STYLE="cursor: pointer;" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="login-btn"
            @click.native.prevent="checkPuzzel"
            >登 录
          </el-button>
        </el-form>
        <p class="tel">官方客服：13303432106</p>
        <p class="pwd-hint">
          <span style="color: red">温馨提示：</span>忘记密码请联系管理员
        </p>
      </div>
    </div>

    <div class="copyright">
      Copyright 2015-2023 山西嘉医信达网络科技有限公司，All rights reserved.
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { getTenantList } from "@/api/user";
import { loginVerify, loginRegister } from "@/api/table";
import { setTenant, setToken, setHomePage } from "@/utils/auth";
import { getLink } from "@/api/links";
import Cookies from "js-cookie";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback();
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码至少是六位"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        loginName: "",
        password: "",
        tenantId: "",
      },
      loginRules: {
        loginName: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      tenantList: [],
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    getTenantList().then((res) => {
      if (res.code === 200) {
        this.tenantList = res.data;

        if (localStorage.getItem("tenantId") != undefined) {
          this.loginForm.tenantId = localStorage.getItem("tenantId");
        } else {
          localStorage.setItem("tenantId", this.tenantList[0].tenantId);
          this.loginForm.tenantId = this.tenantList[0].tenantId;
        }
      }
    });
  },
  methods: {
    depChange(val) {
      localStorage.setItem("tenantId", val);
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    async handleLogin() {
      if (
        typeof this.loginForm.loginName != "string" ||
        this.loginForm.loginName.length < 1
      ) {
        //alert("请输入登录名!");
        this.$message({
          message: "请输入登录名!",
          type: "warning",
          duration: 1500,
        });
        return;
      }
      // this.loading = true;
      this.$store.commit("user/SET_ssoStatus", "");
      //获取单点状态
      const userId = this.$store.state.user.ssoStatus;
      console.log("tenantId", Cookies.get("tenantId"));
      const data = await this.$store.dispatch("user/login", this.loginForm);
      if (data.code == 200) {
        //注册加+验证服务
        if (userId != "" && userId != null && userId != "undefined") {
          loginRegister({
            loginId: data.user.workNumber,
            userId: data.user.workNumber, //系统登录id
            loginname: data.user.workNumber,
          }).then((res) => {
            if (res.code == 200) {
              loginVerify({
                captcha: userId.split("+")[1],
                loginId: data.user.workNumber, //系统登录id
              }).then((res2) => {
                console.log(res.code == 200);
                if (res2.code == 200) {
                  this.$store.commit("user/SET_TOKEN", data.user.id);
                  setToken(data.user.id);
                  this.$router.push({ path: "/" });
                } else {
                  alert(res2.msg);
                }
              });
            } else {
              alert(res.msg);
            }
          });
        } else {
          this.$store.commit("user/SET_TOKEN", data.user.id);
          this.$store.commit("user/SET_TENANT", data.user.tenantId);
          setToken(data.user.id);
          setTenant(data.user.tenantId);

          if (data.user.roleId.indexOf("护士") != -1) {
            setHomePage("病人管理");
            this.$router.push({ path: "/patientHome" });
          } else {
            setHomePage("工作站");
            this.$router.push({ path: "/admin" });
          }
        }
        getLink().then((res) => {
          this.linkList = res.data;
          localStorage.setItem("linkList", JSON.stringify(res.data));
          const data = [];
          for (let i = 0; i < res.data.length; i++) {
            const node = res.data[i];
            data.push(node.location);
          }
          localStorage.setItem("linkListLocal", JSON.stringify(data));
        });
      }

      // this.loading = false;
    },
    checkPuzzel() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.isVerificationShow = true;
          this.handleLogin();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  display: flex;
  height: 100%;
  width: 100%;
  background-image: url("../../icons/img/login-bg.png");
  background-size: 100%;

  .left {
    width: 60%;
    margin: 60px auto 30px;
    color: #fff;
    text-align: center;

    .title {
      font-size: 30px;
      line-height: 40px;
    }

    .sub-title {
      font-size: 20px;
      line-height: 40px;
      margin-top: 10px;
    }

    .hospital-scene {
      margin-top: 20px;
      width: 400px;
      height: 350px;
    }
  }

  .right {
    width: 40%;

    .content {
      width: 360px;
      margin-top: 80px;
      border-radius: 5px;
      background: #fff;

      .logo {
        width: 125px;
        margin-top: 10px;
        margin-left: 10px;
      }

      .login-title {
        text-align: center;
        line-height: 60px;
        font-size: 20px;
      }

      .login-form {
        width: 520px;
        max-width: 100%;
        padding: 0px 20px 20px;

        .svg-container {
          color: #889aa4;
        }

        .el-select,
        .el-input {
          width: 85%;
          margin: 0px 7px;
        }

        .login-btn {
          margin: 0 0 0 6%;
          width: 85%;
          font-size: 16px;
        }
      }

      .tel {
        line-height: 20px;
        text-align: center;
        margin-top: 0;
        font-size: 14px;
        margin-bottom: -10px;
      }

      .pwd-hint {
        line-height: 20px;
        text-align: center;
        font-size: 12px;
        padding-bottom: 10px;
      }
    }
  }

  .copyright {
    position: absolute;
    top: 95%;
    width: 100%;
    height: auto;
    font-size: 14px;
    color: #fff;
    text-align: center;
  }
}
</style>
